<template>
  <div>
  <el-container>

    <el-header id="head">
      <!-- 面包屑导航区 -->
      <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/filecenter">文档中心</a></el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>

    <!-- 卡片区视图区 -->
    <el-card>
    <el-row :gutter="50">
      <el-col :span="5">
      <el-button type="primary" @click="createRootFile">根目录添加文件</el-button>
      </el-col>
      <el-col :span="5">
      <el-button type="primary" @click="createRootDir">根目录添加文件夹</el-button>
      </el-col>
    </el-row>
    <br>

    <!-- 表格 -->
    <el-table
        :data="workList"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        height="460"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        <el-table-column
        prop="name"
        label="名称"
        width="180">
        </el-table-column>
        <el-table-column
        prop="haschildren"
        label="类型"
        width="60">
          <template slot-scope="scope">
          <div class="change-icon">
          <span v-if="scope.row.haschildren"><i class="el-icon-folder-opened"></i></span>
          <span v-if="!scope.row.haschildren"><i class="el-icon-document"></i></span>
          </div>
          </template>  
        </el-table-column>
        <el-table-column
        prop="children"
        label="内含文件数"
        width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.haschildren">{{scope.row.children.length}}</span>
            <span v-if="!scope.row.haschildren"> / </span>
          </template>  
        </el-table-column>
        <el-table-column
        prop="address"
        label="操作">
          <template slot-scope="scope">
            <el-row :gutter="50">
              <el-col :span="1">
                <span v-if="scope.row.haschildren">
                <el-tooltip effect="dark" content="新建文件夹" placement="top" :enterable="false" >
                  <el-button type="primary" icon="el-icon-folder-opened" size="small" round @click="createDir(scope.row.location)"></el-button>
                </el-tooltip>
                </span>
              </el-col>
              <el-col :span="1">
                <span v-if="scope.row.haschildren">
                <el-tooltip effect="dark" content="新建文档" placement="top" :enterable="false" >
                  <el-button type="primary" icon="el-icon-document" size="small" round @click="createFile(scope.row.location)"></el-button>
                </el-tooltip>
                </span>
              </el-col>  
              <el-col :span="1">
                <span v-if="!scope.row.haschildren">
                <el-tooltip  effect="dark" content="修改文件" placement="top" :enterable="false" >
                  <el-button type="info" icon="el-icon-edit" size="small" round @click="editFile(scope.row.name, scope.row.location)"></el-button>
                </el-tooltip>
                </span>
              </el-col>  
              <el-col :span="1">
                <span v-if="scope.row.haschildren">
                <el-tooltip effect="dark" content="删除文件夹" placement="top" :enterable="false">
                  <el-button type="danger" icon="el-icon-close" size="small" round @click="deleteDir(scope.row.location)"></el-button>
                </el-tooltip>
                </span>
                <span v-if="!scope.row.haschildren">
                <el-tooltip effect="dark" content="删除文件" placement="top" :enterable="false">
                  <el-button type="danger" icon="el-icon-close" size="small" round @click="deleteFile(scope.row.location)"></el-button>
                </el-tooltip>
                </span>
              </el-col>  
            </el-row>   
          </template>
        </el-table-column>
    </el-table>

    </el-card>
<!--    选择模板与标题-->
    <el-dialog  :visible.sync="fileVisible" :modal-append-to-body="false" width="80%">
      <el-form :inline="true" :model="q" :rules="pubFormRules" ref="selectRef">
        <el-form-item label="文档模板" prop="template">
          <el-select v-model="q.Template" placeholer="请选择模板" size="small">
            <el-option label="空白" value="empty"></el-option>
            <el-option label="会议纪要" value="meeting"></el-option>
            <el-option label="项目计划" value="plan"></el-option>
            <el-option label="工作总结" value="summary"></el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="文档标题" style="margin-left: 15px;" prop="title">
          <el-input v-model="q.title" placeholder="请输入标题"></el-input>

        </el-form-item>

      </el-form>
      <el-button type="primary" size="small" class="btn-pub" @click="showPubDialogFn">新建</el-button>
    </el-dialog>
    <!--发表文档-->
    <el-dialog :visible.sync="pubDialogVisible" :modal-append-to-body="false"
               fullscreen :before-close="handleClose" @close="dialogCloseFn">
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">

        <el-form-item label="" prop="content">

          <editor
              :key="tinymceFlag"
              ref="editor"
              v-model="pubForm.content"
              :init="tinymceInit">
          </editor>

          <vue-html2pdf
              :show-layout="false"
              :float-layout="true"
              :enable-download="true"
              :preview-modal="false"
              :paginate-elements-by-height="1400"
              :filename="this.fileName"
              :pdf-quality="2"
              :manual-pagination="false"
              pdf-format="a4"
              pdf-orientation="landscape"
              pdf-content-width="800px"
              @progress="onProgress($event)"
              @hasStartedGeneration="hasStartedGeneration()"
              @hasGenerated="hasGenerated($event)"
              ref="html2Pdf"

          >
            <section slot="pdf-content">
              <!-- PDF Content Here -->
              <span id="report" v-html="pubForm.content"></span>
            </section>
          </vue-html2pdf>

<!--          <Tinymce ref="tinymce" v-model="pubForm.content"  />-->
        </el-form-item>
        <el-form-item>
          <!--          <el-button type="primary" @click="pubArticleFn">发布</el-button>-->
          <el-button type="success" size="small" @click="handleSaveToPdf">保存为Pdf</el-button>
          <el-button type="primary" size="small" @click="pubArticleFn">发布</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>
<!--    命名文件夹-->
    <el-dialog  :visible.sync="dirVisible" :modal-append-to-body="false" width="80%">
      <el-form :inline="true" :model="dirForm" :rules="dirRules" ref="dirRef">

        <el-form-item label="文件夹名" style="margin-left: 15px;" prop="title">
          <el-input v-model="dirForm.dirName" placeholder="请输入文件夹名"></el-input>

        </el-form-item>

      </el-form>
      <el-button type="primary" size="small" class="btn-pub" @click="dirNow">确定</el-button>
    </el-dialog>
  </el-container>
  </div>
</template>

<script>
import qs from 'qs';
import Editor from "@tinymce/tinymce-vue";
import VueHtml2pdf from "vue-html2pdf";
export default {
  components:{
    VueHtml2pdf,
    'editor': Editor
  },
  activated() {
    this.tinymceFlag++
  },
  data(){
    return {
      fileName:'',
      tinymceFlag: 1,
      tinymceInit: {},
      q:{
        Template:'',
        title:''
      },
      pubFormRules:{
        title: [
          {required: true, message: '请输入文章标题', trigger: 'blur'},
          {min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur'}
        ],
        content: [{required: true, message: '请输入文章内容', trigger: 'blur'}],
      },
      dirRules:{
        name: [{required: true, message: '请输入文件名', trigger: 'blur'}]
      },
      fileVisible: false,
      dirVisible: false,
      //文档中心的文档列表，默认为空
      workList: [],
      //文档中心根目录
      workRoot: '',
      pubForm: {
        title:'',
        content:'',
        location: ''
      },
      dirForm: {
        location: '',
        dirName: ''
      },
      pubDialogVisible: false
    } 
  },

  created(){
    this.getWorkList();
    this.initEditor();
  },
  // computed(){
  //   this.htmlToPdfOptions()
  // },
  methods:{
    //html2pdf的函数
    // htmlToPdfOptions() {
    //   return {
    //     margin: 0,
    //
    //     filename: "我是pdf.pdf",
    //
    //     image: {
    //       type: "jpeg",
    //       quality: 0.98,
    //     },
    //
    //     enableLinks: true,
    //
    //     html2canvas: {
    //       scale: 2,
    //       useCORS: true,
    //     },
    //
    //     jsPDF: {
    //       unit: "in",
    //       format: 'a4',
    //       orientation: 'portrait',
    //     },
    //   };
    // },
    handleSaveToPdf() {
      this.fileName = this.q.title
      console.log(this.fileName)
      this.$refs.html2Pdf.generatePdf()
    },
    onProgress() {

    },
    hasStartedGeneration() {

    },
    hasGenerated() {

    },
    //上传文档
    pubArticleFn(){
      this.$refs.pubFormRef.validate(async valid =>{
        if(valid){
          console.log("title: "+this.q.title)
          console.log("location: "+this.pubForm.location)
          this.$axios({
            method: 'post',
            url: '/works/save',
            data: qs.stringify({
              usertoken: this.$store.getters.getUser.user.usertoken,
              teamtoken:this.$store.getters.getGroup.group.grouptoken,
              filename: this.q.title,
              contents: this.pubForm.content,
              location: this.pubForm.location
            })
          }).then(res => {                  /* res 是 response 的缩写 */
            console.log(res);
            this.getWorkList();

          })
              .catch(err => {                 /* 请求若出现路由找不到等其它异常，则在终端输出错误信息 */
                console.log(err);
              })
          this.q.title = ''
          this.pubForm.content = ''
          this.pubForm.location = ''
          this.pubDialogVisible = false
          this.rewriteVisible = false
          this.fileVisible = false

        }
        else{
          return false
        }
      })
    },
    //初始化文本编辑器
    initEditor() {
      this.tinymceInit = {
        language: 'zh_CN',
        height: 580,
        width: 1200,
        branding: false,
        fontsize_formats:
            '12px 13px 14px 15px 16px 17px 18px 19px 20px 22px 24px 26px 28px 30px 32px 34px 40px 50px',
        toolbar:
            'formatselect fontselect | bold italic strikethrough  fontsizeselect | link image | forecolor backcolor' +
            ' | numlist bullist | table hr',
        plugins:
            'lists table hr',
      }
      this.tinymceFlag++
    },
    //文档是否符合要求
    dialogCloseFn() {
      this.$refs.pubFormRef.resetFields()
    },
    //关闭dialog时确认
    async handleClose(done) {
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult === 'cancel')return
      done()
    },
    //上传文档
    showPubDialogFn() {

      this.$refs.selectRef.validate(async valid => {
        if(valid){
          // this.fileName = this.q.title
          // console.log(this.fileName)
          let templateName = ''
          if(this.q.Template==='empty'){
            templateName = '空白'
          }
          else if(this.q.Template==='meeting'){
            templateName = '会议纪要'
          }
          else if(this.q.Template==='summary'){
            templateName = '工作周报'
          }
          else {
            templateName = '项目计划'
          }
          if(templateName.length!==0){
            console.log(templateName+"@"+this.$store.getters.getUser.user.usertoken)
            this.$axios({
              method: 'post',
              url: '/template/load',
              data: qs.stringify({
                usertoken: this.$store.getters.getUser.user.usertoken,
                templatename: templateName+"@0",
              })
            }).then(res => {
              console.log(res)
              this.pubForm.content = res.data.contents

            })
                .catch(err => {
                  console.log(err)
                })
          }
          else {
            this.pubForm.content = ''
          }
          this.pubForm.title = ''
          this.pubDialogVisible = true
        }
        else {
          return false
        }
      })

    },
    //获取文档目录结构
    getWorkList(){
      const usertoken = this.$store.getters.getUser.user.usertoken;
      const teamtoken = this.$store.getters.getGroup.group.grouptoken;
      //console.log(this.$store.getters.getProject.project.projecttoken);
      //console.log(this.usertoken);
      // console.log(this.sort);
      // console.log(this.searchName);
      this.$axios({
        method: "post" /* 指明请求方式，可以是 get 或 post */,
        url: "/works/list" /* 指明后端 api 路径，由于在 main.js 已指定根路径，因此在此处只需写相对路由 */,
        data: qs.stringify({
          /* 需要向后端传输的数据，此处使用 qs.stringify 将 json 数据序列化以发送后端 */
          usertoken: usertoken,
          teamtoken: teamtoken,
        }),
      })
      .then((res) => {
        /* res 是 response 的缩写 */
        console.log(res.data);
        // console.log(res.data.root);
        if(!res.data.success){
          this.$message.error(res.data.message);
        }
        else{
          this.workList = res.data.message;
          this.workRoot = res.data.root;
        }
      });
    },
    //上传文件夹
    dirNow(){
      this.$refs.dirRef.validate(async valid => {
            if(valid){
              console.log("location: "+this.dirForm.location)
              this.$axios({
                method: 'post',
                url: '/works/mkdir',
                data: qs.stringify({
                  usertoken: this.$store.getters.getUser.user.usertoken,
                  teamtoken: this.$store.getters.getGroup.group.grouptoken,
                  location: this.dirForm.location,
                  dirname: this.dirForm.dirName
                })
              })
                  .then(res => {
                    console.log(res)
                    this.dirForm.location = ''
                    this.dirForm.dirName = ''
                    this.dirVisible = false
                    this.getWorkList()
                  })
                  .catch(err => {
                    console.log(err)
                  })
            }
            else {
              return false
            }
      })
    },
    //在指定路径新建文件夹
    createDir(location) {
      console.log(location)
      if(location.indexOf('group')===-1){
        this.$message.error("该路径下不能新建文件夹！");
      }
      else {
        this.dirVisible = true
        this.dirForm.location = location
      }

    },

    //在指定路径新建文件
    createFile(location) {

      if(location.indexOf('group')===-1){
        this.$message.error("该路径下不能新建文件！");
      }
      else {
        // this.$refs.pubFormRef.resetFields()
        this.pubForm.title = ''
        this.q.title = ''
        this.pubForm.location = ''
        this.fileVisible = true
        this.pubForm.location = location
      }
    },

    //删除指定路径下的文件夹
    deleteDir(location) {
      this.deleteFile(location)
    },

    //删除指定路径下的文件
    deleteFile(location) {
      this.$axios({
        method: 'post',
        url: '/works/drop',
        data: qs.stringify({
          usertoken: this.$store.getters.getUser.user.usertoken,
          teamtoken: this.$store.getters.getGroup.group.grouptoken,
          location: location
        })
      })
          .then(res => {
            console.log(res)
            this.getWorkList()
          })
          .catch(err => {
            console.log(err)
          })
    },

    //编辑指定路径下的文件
    editFile(title, location) {
      this.$axios({
        method:'post',
        url: '/works/load',
        data: qs.stringify({
          usertoken: this.$store.getters.getUser.user.usertoken,
          teamtoken:this.$store.getters.getGroup.group.grouptoken,
          location: location
        })
      }).then(res => {                  /* res 是 response 的缩写 */
        this.pubForm.content = res.data.contents
        this.q.title = title
        this.pubForm.location = location
        console.log(res)
      })
          .catch(err => {                 /* 请求若出现路由找不到等其它异常，则在终端输出错误信息 */
            console.log(err);
          })
      //quillEditor.inserted(this.docDetail)
      this.pubDialogVisible = true
    },

    //根目录下创建文件夹
    //根目录路径可以直接使用this.workRoot
    createRootDir() {
      this.dirVisible = true
      this.dirForm.location = this.workRoot
    },

    //根目录下创建文件
    //根目录路径可以直接使用this.workRoot
    createRootFile() {
      this.fileVisible = true
      this.pubForm.location = this.workRoot
    },

  },
}
</script>

<style>
.change-icon{
    font-size: 20px;
}
</style>